package icu.lookyousmileface.boot_admin.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author starrysky
 * @title: LoginInterceptor
 * @projectName boot_admin
 * @description: 定制拦截器，配置需要放进容器
 * <div>机制：请求->pre->对应的处理器->post->页面渲染->after->浏览器</div>
 * @date 2021/1/110:26 下午
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       log.info("preHandler执行");
        String requestURI = request.getRequestURI();
        log.info("拦截路径为："+requestURI);
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
//        true放行/false拦截
       if (loginUser!=null){
           return true;
       }
       request.setAttribute("msg","请先登陆");
        //为了可以提示msg，使用转发器
        request.getRequestDispatcher("/").forward(request,response);
       return false;
    }

    /**
     * 目标方法执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    log.info("postHandle执行");
    }

    /**
     * <div>页面渲染之后</div>
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行");
    }
}
